package com.xuan.common.core.utils;

import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class ThreadLocalUtils {


    private static final TransmittableThreadLocal<Map<String,Object>> THREAD_LOCAL
            = new TransmittableThreadLocal<>();

    private ThreadLocalUtils() {

    }

    public static void set(String key, Object value) {
        Map<String, Object> localMap = getLocalMap();
        localMap.put(key, value);
    }

    public static <T> T get(String key, Class<T> clazz) {
        Map<String, Object> localMap = getLocalMap();
        return (T) localMap.getOrDefault(key, null);

    }

    public static boolean mapIsNull() {
        return THREAD_LOCAL.get() == null;
    }

    public static void clear() {
        THREAD_LOCAL.remove();
    }

    private static Map<String,Object> getLocalMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new HashMap<>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }

}
